package org.jeecg.modules.alarmSettings.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.DySmsEnum;
import org.jeecg.common.util.DySmsHelper;
import org.jeecg.modules.alarmSettings.entity.AlarmSettings;
import org.jeecg.modules.alarmSettings.mapper.AlarmSettingsMapper;
import org.jeecg.modules.alarmSettings.service.IAlarmSettingsService;
import org.jeecg.modules.errorLog.service.IErrorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.List;

/**
 * @Description: 报警设置
 * @Author: jeecg-boot
 * @Date:   2023-10-16
 * @Version: V1.0
 */
@Service
@Slf4j
public class AlarmSettingsServiceImpl extends ServiceImpl<AlarmSettingsMapper, AlarmSettings> implements IAlarmSettingsService {

    @Autowired
    private IErrorService errorService;

    @Override
    public void sendMessage(List<String> name, String message) {
        LambdaQueryWrapper<AlarmSettings> wrapper = Wrappers.lambdaQuery();
        wrapper.in(AlarmSettings::getName, name);
        List<AlarmSettings> alarmSettings = baseMapper.selectList(wrapper);
        for(AlarmSettings alarmSetting : alarmSettings){
            if (1 == alarmSetting.getEnable()){
                //手机号
                String phone = alarmSetting.getPhone();
                //消息模版,此处是登录验证模版
                DySmsEnum templateCode = DySmsEnum.REGISTER_TEMPLATE_CODE;
                //模版所需参数
                JSONObject obj = new JSONObject();
                obj.put("code", message);
                try {
                    DySmsHelper.sendSms(phone, obj, templateCode);
                    log.info("发送成功");
                } catch (ClientException e) {
                    errorService.saveError(e.getMessage(), String.valueOf(e.getCause()));
                }
            }
        }
    }
}
